package com.bdqn.crm.controller;
import com.bdqn.crm.config.shiro.MyShiroRealm;
import com.bdqn.crm.pojo.Right;
import com.bdqn.crm.pojo.Role;
import com.bdqn.crm.pojo.User;
import com.bdqn.crm.service.RoleService;
import com.bdqn.crm.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class IndexController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private String SHIRO_LOGIN_COUNT="shiro_login_count";


    /**
     * 去登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    /**
     * 执行登录操作
*/
    @PostMapping("/login")
    public String doLogin(HttpSession session, String usrName, String usrPassword, Model model) {
    // User loginUser = userService.login(usrName, usrPassword);
    // session.setAttribute("loginUser", loginUser);
    // return "redirect:/main";
   try {
        usrPassword=userService.encryptPassword(usrPassword);
       UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword);
       Subject subject= SecurityUtils.getSubject();
       subject.login(token);//认证登录
       //认证登录成功，清空登录计数
        stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);
            // 认证(登录)成功
            User user=(User) subject.getPrincipal();
            //用户权限
            Role role =user.getRole();
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("loginUser",user);
            //清空缓存权限
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm= (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();
            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","用户名或密码失败，登录失败！");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用，登录失败！");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("message","认证异常，登录失败！");
            return "login";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 跳转到主页
     */
    @GetMapping("/main")
    public String toMain() {
        return "main";
    }

    /**
     * 退出登录-
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}

